/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
namespace UpdateViews
{
    class Program
    {

        /// <summary>
        /// Make sure you update these hard-coded paths to match your system. _LOOK_
        /// </summary>
        const string CONST_LOCAL_VIEW = @"C:\svn\Pos\OceansidePos\Kiosk\Database\LocalDominicaModel.Views.cs";
        const string CONST_REMOTE_VIEW = @"C:\svn\Pos\OceansidePos\Kiosk\Database\RemoteDominicaModel.Views.cs";

        const string CONST_LOCAL_MODEL = @"C:\svn\Pos\OceansidePos\Kiosk\Database\LocalDominicaModel.Designer.cs";
        const string CONST_REMOTE_MODEL = @"C:\svn\Pos\OceansidePos\Kiosk\Database\RemoteDominicaModel.Designer.cs";
        const string CONST_COMMAND = @"C:\Program Files (x86)\Common Files\microsoft shared\TextTemplating\10.0\TextTransform.exe";
        const string CONST_LOCAL_TEMPLATE = @"C:\svn\Pos\OceansidePos\Kiosk\Database\LocalDominicaModel.Views.tt";
        const string CONST_REMOTE_TEMPLATE = @"C:\svn\Pos\OceansidePos\Kiosk\Database\RemoteDominicaModel.Views.tt";

        /// <summary>
        /// The main POS application can run off of a local database or a remote one.  That is why you will see
        /// the #if's below.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            ///1) Update the remote and local models to assure the ifdefs are present.
            IEnumerable<string> linesE = File.ReadLines(CONST_LOCAL_MODEL);
            List<string> lines = new List<string>(linesE);
            if (!lines.First().Equals("#if _LOCALDB"))
            {
                lines.Insert(0, "#if _LOCALDB");
                lines.Add("#endif");
                StreamWriter sr = new StreamWriter(CONST_LOCAL_MODEL, false);
                foreach (string s in lines)
                {
                    sr.WriteLine(s);
                }
                sr.Flush();
                sr.Close();
            }

            linesE = File.ReadLines(CONST_REMOTE_MODEL);
            lines = new List<string>(linesE);
            if (!lines.First().Equals("#if !_LOCALDB"))
            {
                lines.Insert(0, "#if !_LOCALDB");
                lines.Add("#endif");
                StreamWriter sr = new StreamWriter(CONST_REMOTE_MODEL, false);
                foreach (string s in lines)
                {
                    sr.WriteLine(s);
                }
                sr.Flush();
                sr.Close();
            }


            ///2) Update the templates for faster Entity Framework Performance
            string outmessage = "";
            string errormessage = "";
            ExecuteShellCommand(CONST_COMMAND, CONST_LOCAL_TEMPLATE, ref outmessage, ref errormessage);
            Console.WriteLine(outmessage);
            Console.WriteLine(errormessage);
            ExecuteShellCommand(CONST_COMMAND, CONST_REMOTE_TEMPLATE, ref outmessage, ref errormessage);
            Console.WriteLine(outmessage);
            Console.WriteLine(errormessage);

            ///3) Assure the templates have the ifdefs.
            linesE = File.ReadLines(CONST_REMOTE_VIEW);
            lines = new List<string>(linesE);
            if (!lines.First().Equals("#if !_LOCALDB"))
            {
                lines.Insert(0, "#if !_LOCALDB");
                lines.Add("#endif");
                StreamWriter sr = new StreamWriter(CONST_REMOTE_VIEW, false);
                foreach (string s in lines)
                {
                    sr.WriteLine(s);
                }
                sr.Flush();
                sr.Close();
            }

            linesE = File.ReadLines(CONST_LOCAL_VIEW);
            lines = new List<string>(linesE);
            if (!lines.First().Equals("#if _LOCALDB"))
            {
                lines.Insert(0, "#if _LOCALDB");
                lines.Add("#endif");
                StreamWriter sr = new StreamWriter(CONST_LOCAL_VIEW, false);
                foreach (string s in lines)
                {
                    sr.WriteLine(s);
                }
                sr.Flush();
                sr.Close();
            }
        }

        /// <summary>
        /// Execute a shell command
        /// </summary>
        /// <param name="_FileToExecute">File/Command to execute</param>
        /// <param name="_CommandLine">Command line parameters to pass</param> 
        /// <param name="_outputMessage">returned string value after executing shell command</param> 
        /// <param name="_errorMessage">Error messages generated during shell execution</param> 
        private static void ExecuteShellCommand(string _FileToExecute, string _CommandLine, ref string _outputMessage, ref string _errorMessage)
        {
            // Set process variable
            // Provides access to local and remote processes and enables you to start and stop local system processes.
            System.Diagnostics.Process _Process = null;
            try
            {
                _Process = new System.Diagnostics.Process();

                // invokes the cmd process specifying the command to be executed.
                string _CMDProcess = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\cmd.exe", new object[] { Environment.SystemDirectory });

                // pass executing file to cmd (Windows command interpreter) as a arguments
                // /C tells cmd that we want it to execute the command that follows, and then exit.
                string _Arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/C {0}", new object[] { _FileToExecute });

                // pass any command line parameters for execution
                if (_CommandLine != null && _CommandLine.Length > 0)
                {
                    _Arguments += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { _CommandLine, System.Globalization.CultureInfo.InvariantCulture });
                }

                // Specifies a set of values used when starting a process.
                System.Diagnostics.ProcessStartInfo _ProcessStartInfo = new System.Diagnostics.ProcessStartInfo(_CMDProcess, _Arguments);
                // sets a value indicating not to start the process in a new window. 
                _ProcessStartInfo.CreateNoWindow = true;
                // sets a value indicating not to use the operating system shell to start the process. 
                _ProcessStartInfo.UseShellExecute = false;
                // sets a value that indicates the output/input/error of an application is written to the Process.
                _ProcessStartInfo.RedirectStandardOutput = true;
                _ProcessStartInfo.RedirectStandardInput = true;
                _ProcessStartInfo.RedirectStandardError = true;
                _Process.StartInfo = _ProcessStartInfo;

                // Starts a process resource and associates it with a Process component.
                _Process.Start();

                // Instructs the Process component to wait indefinitely for the associated process to exit.
                _errorMessage = _Process.StandardError.ReadToEnd();
                _Process.WaitForExit();

                // Instructs the Process component to wait indefinitely for the associated process to exit.
                _outputMessage = _Process.StandardOutput.ReadToEnd();
                _Process.WaitForExit();
            }
            catch (Win32Exception _Win32Exception)
            {
                // Error
                Console.WriteLine("Win32 Exception caught in process: {0}", _Win32Exception.ToString());
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }
            finally
            {
                // close process and do cleanup
                _Process.Close();
                _Process.Dispose();
                _Process = null;
            }
        }
    }
}
